package cn.gan.loveofsoul.service.impl;

import cn.gan.loveofsoul.commons.result.StatusCode;
import cn.gan.loveofsoul.commons.utils.FileUtil;
import cn.gan.loveofsoul.commons.utils.UUIDUtil;
import cn.gan.loveofsoul.exception.BusinessException;
import cn.gan.loveofsoul.service.IFileUploadService;
import cn.hutool.core.map.MapUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: ganwh
 * @Since: 2023/11/8 10:04
 */
@Service
public class FileUploadServiceImpl implements IFileUploadService {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);
    @Autowired
    private GridFsTemplate gridFsTemplate;

    /**
     * 功能描述: 上传文件
     *
     * @param clientFile
     * @return java.lang.String
     * @author ganwh 2023/11/8 10:35
     */
    @Override
    public Map<String, String> uploadFile(MultipartFile clientFile) {
        try {
            String fileId = UUIDUtil.getUUID32Bits();
            String fileName = clientFile.getOriginalFilename();
            DBObject metadata = new BasicDBObject("fileId", fileId);
            metadata.put("fileType", FileUtil.getExtensionName(fileName));
            ObjectId objectId = gridFsTemplate.store(clientFile.getInputStream(), fileName, clientFile.getContentType(), metadata);
            logger.error("上传文件成功 -> {}, 文件ID{}", objectId, fileId);

            HashMap<String, String> resultMap = MapUtil.newHashMap();
            resultMap.put("fileId", fileId);
            resultMap.put("fileName", fileName);
            return resultMap;
        } catch (IOException ex) {
            logger.error("上传文件失败 -> ", ex);
            throw new BusinessException(StatusCode.ERROR, "上传失败");
        }
    }
}
